<?php
/**
 * oscshop2 B2C电子商务系统
 *
 * ==========================================================================
 * @link      http://www.oscshop.cn/
 * @copyright Copyright (c) 2015-2017 oscshop.cn. 
 * @license   http://www.oscshop.cn/license.html License
 * ==========================================================================
 *
 * @author    李梓钿
 *
 * 会员登录注册相关
 */
 
namespace osc\mobile\controller;
use osc\common\controller\Base;
use think\Db;
use think\captcha\Captcha;


class Login extends Base{	
	//注册
	function reg(){	
		$sharemobile = session("sharemobile");
		if(request()->isPost()){
			
			$data=input('post.');

			$r= osc_service('common','Member')->reg($data);
			
			if(isset($r['error'])){
				return $r;
			}elseif($r['success']){
				
				if(!$url=cookie('jump_url')){						
					$url=url('/mobile');
				}
				session("username",$data['username']);
				if(1==config('reg_check')){
					return array('success'=>'注册成功，请等待管理员审核','check'=>1,'url'=>$url);
				}else{					
					return array('success'=>'注册成功','check'=>0,'url'=>$url);
				}
				
			}
			
		}
		if(session("smsnum"))
		{
			session("smsnum",'0');
		}
		$this->assign('sharemobile',$sharemobile);
		$this->assign('SEO',array('title'=>'注册-'.config('SITE_TITLE')));
		$this->assign('top_title','注册');
        return $this->fetch();
    }
	//登录
	function login(){
		if(request()->isGet()){
			$share = input('get.');
//			var_dump($share);exit;
			if(empty($share))
			{
				if($share['sharemobile'])
				{
					if(is_numeric($share['sharemobile']))
					{
						session('sharemobile',$share['sharemobile']);
					}
				}
			}
		}
		

		if(request()->isPost()){
			$data=input('post.');	
			
			$r=osc_service('common','Member')->login($data);	
			
			if(isset($r['error'])){
				return $r;
			}elseif($r['success']){
				osc_service('mobile','user')->set_cart_total($r['total']);		
				
				if(!$url=cookie('jump_url')){						
						$url=url('/mobile/user/index');
				}
				session("username",$data['username']);	
				return array('success'=>'登录成功','url'=>$url);
			}
		}
		if(session("smsnum"))
		{
			session("smsnum",'0');
		}
		$this->assign('SEO',array('title'=>'登录-'.config('SITE_TITLE')));
		$this->assign('top_title','登录');
        return $this->fetch();
    }
    //找回密码
    function find(){
    	$this->assign('SEO',array('title'=>'找回密码-'.config('SITE_TITLE')));

		if(request()->isPost()){
			$data=input('post.');
            
            //判断短信验证码是否正确

			$r=osc_service('common','Member')->find($data);
			if(isset($r['error'])){
				return $r;
			}

			return array('success'=>'修改密码成功','url'=>"/mobile/login/login");
		}


		$this->assign('top_title','找回密码');
    	return $this->fetch();
    }

	//退出
	function logout(){
		cookie(null);
		session(null);

		$this->redirect(url('/mobile/login/login'));
	}
	//验证码
 	function verify(){	 	
		$captcha = new Captcha((array)Config('captcha'));
		return $captcha->entry(1);	 	
    }

    public function regsms()
	{
		$data=input('post.');	
		//var_dump($data);
		//$data['mobile']  = $data['from_user'] = $mobile = trim(input('post.username', null));
		//echo $data['mobile'];
		//echo "infosys";
		//$this->sendsms($data['mobile']);
		try {
                if($data['mobile']==null)
				{
					//throw new \Exception('手机号码不能为空');
					return array('error'=>'手机号码不能为空');
				}

                if($data['mobile']=="")
				{
					//throw new \Exception('手机号码不能为空');
					return array('error'=>'手机号码不能为空');
				}

            } catch (\Exception $e) {

                $this->assign([

                    'error' => $e->getMessage(),

                ]);

            } 
		
		//$this->sendsms($data['mobile']);
            $r=osc_service('common','Member')->sendsms_common($data['mobile'],'regsms');

		
	}

	public function send2pwd()
	{
		//$data=input('post.');	
		//var_dump($data);
		//$data['mobile']  = $data['from_user'] = $mobile = trim(input('post.username', null));
		//echo $data['mobile'];
		//echo "infosys";
		//$this->sendsms($data['mobile']);
		$mobile = session("username");
		
		$ret = "0";
		if($mobile)
		{
           //$ret =  $this->sendsms_common($mobile,'send2pwd');
           $r=osc_service('common','Member')->sendsms_common($mobile,'send2pwd');

		}

		//retrun $ret;
	}
	
	


	public function sendsms_password($mobile)
	{
		$target = "https://sms.aliyuncs.com/?";  
	  
		//$withdraw = M('Withdraw');
        //$member = M('Member');
        //查找member_id对应的交易密码
        //$where['member_id'] = session('USER_KEY_ID');
        //查找member表uid对应信息（交易密码，可以金额，冻结金额）
        //$mem_data = $member->field('phone')->where($where)->find();

        if($mobile)
		{
           //$ret =  $this->sendsms_common($mobile,'send2pwd');
           $r=osc_service('common','Member')->sendsms_common($mobile,'FINDSMS');

		}


		
	}

    
    //短信验证码
     function sendsmspwd($mobile)
	 {
		$target = "https://sms.aliyuncs.com/?";  
	  
		//$withdraw = M('Withdraw');
        //$member = M('Member');
        //查找member_id对应的交易密码
        //$where['member_id'] = session('USER_KEY_ID');
        //查找member表uid对应信息（交易密码，可以金额，冻结金额）
        //$mem_data = $member->field('phone')->where($where)->find();
		$phone=$mobile;
		if(($phone!=null)||($phone!=''))
		{
			$target = "https://sms.aliyuncs.com/?";  
			  
			$mobile_code = $this->random(6,1);  
			// 注意使用GMT时间  
			date_default_timezone_set("GMT");  
			$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601规范  
			$accessKeyId = 'LTAICBmlEOvwfsJd';      // 这里填写您的Access Key ID  
			$accessKeySecret = 'zC51CTlzLPne09rO9tIFcJAaH6mrGP';  // 这里填写您的Access Key Secret  
			$ParamString="{\"sms\":\"".strval($mobile_code)."\"}";  
			session('FINDSMS',strval($mobile_code));  
			$data = array(  
				// 公共参数  
				'SignName'=>'茶马古道农业发展',  
				'Format' => 'XML',  
				'Version' => '2016-09-27',  
				'AccessKeyId' => $accessKeyId,  
				'SignatureVersion' => '1.0',  
				'SignatureMethod' => 'HMAC-SHA1',  
				'SignatureNonce'=> uniqid(),  
				'Timestamp' => date($dateTimeFormat),  
				// 接口参数  
				'Action' => 'SingleSendSms',  
				'TemplateCode' => 'SMS_86070013',  
				'RecNum' => $phone,  
				'ParamString' => $ParamString  
			);  
			// 计算签名并把签名结果加入请求参数  
			//echo $data['Version']."<br>";  
			//echo $data['Timestamp']."<br>";  
			$data['Signature'] = $this->computeSignature($data, $accessKeySecret);  
			// 发送请求  
				  
			$result = $this->xml_to_array($this->https_request($target.http_build_query($data)));  			
		}
	}



	function random($length = 6 , $numeric = 0) {  
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);  
		if($numeric) {  
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));  
		} else {  
			$hash = '';  
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';  
			$max = strlen($chars) - 1;  
			for($i = 0; $i < $length; $i++) {  
				$hash .= $chars[mt_rand(0, $max)];  
			}  
		}  
		return $hash;  
	}


	  
	function percentEncode($str)  
	{  
		// 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范  
		$res = urlencode($str);  
		$res = preg_replace('/\+/', '%20', $res);  
		$res = preg_replace('/\*/', '%2A', $res);  
		$res = preg_replace('/%7E/', '~', $res);  
		return $res;  
	}  
	  
	  
	function computeSignature($parameters, $accessKeySecret)  
	{  
		// 将参数Key按字典顺序排序  
		ksort($parameters);  
		// 生成规范化请求字符串  
		$canonicalizedQueryString = '';  
		foreach($parameters as $key => $value)  
		{  
		$canonicalizedQueryString .= '&' . $this->percentEncode($key)  
			. '=' . $this->percentEncode($value);  
		}  
		// 生成用于计算签名的字符串 stringToSign  
		$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));  
		//echo "<br>".$stringToSign."<br>";  
		// 计算签名，注意accessKeySecret后面要加上字符'&'  
		$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));  
		return $signature;  
	}  
	
    function do_get($app_key, $app_secret, $request_host, $request_uri, $request_method, $request_paras, &$info) {
		ksort($request_paras);
		$request_header_accept = "application/json;charset=utf-8";
		$content_type = "";
		$headers = array(
				'X-Ca-Key' => $app_key,
				'Accept' => $request_header_accept
				);
		ksort($headers);
		$header_str = "";
		$header_ignore_list = array('X-CA-SIGNATURE', 'X-CA-SIGNATURE-HEADERS', 'ACCEPT', 'CONTENT-MD5', 'CONTENT-TYPE', 'DATE');
		$sig_header = array();
		foreach($headers as $k => $v) {
			if(in_array(strtoupper($k), $header_ignore_list)) {
				continue;
			}
			$header_str .= $k . ':' . $v . "\n";
			array_push($sig_header, $k);
		}
		$url_str = $request_uri;
		$para_array = array();
		foreach($request_paras as $k => $v) {
			array_push($para_array, $k .'='. $v);
		}
		if(!empty($para_array)) {
			$url_str .= '?' . join('&', $para_array);
		}
		$content_md5 = "";
		$date = "";
		$sign_str = "";
		$sign_str .= $request_method ."\n";
		$sign_str .= $request_header_accept."\n";
		$sign_str .= $content_md5."\n";
		$sign_str .= "\n";
		$sign_str .= $date."\n";
		$sign_str .= $header_str;
		$sign_str .= $url_str;

		$sign = base64_encode(hash_hmac('sha256', $sign_str, $app_secret, true));
		$headers['X-Ca-Signature'] = $sign;
		$headers['X-Ca-Signature-Headers'] = join(',', $sig_header);
		$request_header = array();
		foreach($headers as $k => $v) {
			array_push($request_header, $k .': ' . $v);
		}

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, $request_host . $url_str);
		//curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLINFO_HEADER_OUT, true);
		curl_setopt($ch, CURLOPT_VERBOSE, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $request_header);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$ret = curl_exec($ch);
		$info = curl_getinfo($ch);
		curl_close($ch);
		return $ret;
	}
	
	function https_request($url)  
	{  
		$curl = curl_init();  
		curl_setopt($curl, CURLOPT_URL, $url);  
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
		$data = curl_exec($curl);  
		if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}  
		curl_close($curl);  
		return $data;  
	}  
	function xml_to_array($xml){  
		$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";  
		if(preg_match_all($reg, $xml, $matches)){  
			$count = count($matches[0]);  
			for($i = 0; $i < $count; $i++){  
			$subxml= $matches[2][$i];  
			$key = $matches[1][$i];  
				if(preg_match( $reg, $subxml )){  
					$arr[$key] = $this->xml_to_array( $subxml );  
				}else{  
					$arr[$key] = $subxml;  
				}  
			}  
		}  
		return @$arr;  
	}    


    

}
